package com.example.day08;


import com.example.config.ConstantEnumIFace;
import com.example.day07.ConstantEnumsTypeHandler;
import lombok.Setter;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;

/**
 * @author jeff
 * @time 2023/4/30 22:19
 */
@Configuration
@Setter
public class ConstantEnumConfiguration implements ApplicationContextAware, ResourceLoaderAware {

    @Value("${custom.constants.enum.path:com.example.constract}")
    private String enumPath;


    private ResourceLoader resourceLoader;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        //从spring容器获取sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = applicationContext.getBean(SqlSessionFactory.class);
        //获取typeHandler注册器
        TypeHandlerRegistry typeHandlerRegistry = sqlSessionFactory.getConfiguration().getTypeHandlerRegistry();
        //注册typeHandler
        try {
            ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
            MetadataReaderFactory metaReader = new CachingMetadataReaderFactory(resourceLoader);
            String s = "classpath*:" + enumPath.replace(".", "/") + "/*.class";
            Resource[] resources = resolver.getResources(s);
            for (Resource r : resources) {
                MetadataReader reader = metaReader.getMetadataReader(r);
                Class<?> aClass = Class.forName(reader.getClassMetadata().getClassName());
                if (ConstantEnumIFace.class.isAssignableFrom(aClass)) {
                    typeHandlerRegistry.register(aClass, ConstantEnumsTypeHandler.class);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
}
